﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using BHair.Report;
using System.Drawing.Printing;


namespace BHair.Report
{
    public partial class frmtizhongbianhua : WeifenLuo.WinFormsUI.Docking.DockContent
    {
        public frmtizhongbianhua()
        {
            InitializeComponent();
        }
        string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
        private void button1_Click(object sender, EventArgs e)
        {
            cx();
        }
        public void cx()
        {
            //建立datetable
            DataTable dt = new DataTable();
            string sql;
            //创建列
            dt.Columns.Add("卡号",typeof(string));
            dt.Columns.Add("姓名", typeof(String));
            dt.Columns.Add("起始体重(公斤)", typeof(String));
            dt.Columns.Add("当前体重（公斤）", typeof(String));
            dt.Columns.Add("差额（公斤）",typeof(string));
            //查询卡号姓名赋值
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            if (textBox1.Text == string.Empty)
            {
                 sql =string.Format("SELECT distinct jcxf.cardid,member.mname FROM [jcxf] left join member on jcxf.cardid=member.mid where jcxf.riqi>=convert(datetime,'{0} 00:00:00',120) and jcxf.riqi<=convert(datetime,'{1} 23:59:59',120)", dateTimePicker1.Text,dateTimePicker2.Text);
                SqlCommand comm = new SqlCommand(sql, conn);
                SqlDataReader sdr = comm.ExecuteReader();
                SqlConnection conn1 = new SqlConnection(constr);
                SqlConnection conn2 = new SqlConnection(constr);
                conn2.Open();
                decimal maxcs;
                decimal mincs;
                decimal ce;
                object obj1;
                object obj2;
                string ktime = dateTimePicker1.Text;
                string etime = dateTimePicker2.Text;
                conn1.Open();
                while (sdr.Read())
                {
                    DataRow dr = dt.NewRow();
                    if (textBox1.Text == string.Empty)
                    {
                        dr["卡号"] = sdr["cardid"].ToString();
                        dr["姓名"] = sdr["mname"].ToString();
                    }
                    else
                    {
                        dr["卡号"] = sdr["mid"].ToString();
                        dr["姓名"] = sdr["mname"].ToString();

                    }
                    //查询最大值与最小值并赋值
                    string sql1 = string.Format("SELECT  [bz] FROM [jcxf] join items on jcxf.xmid=items.iid where cardid='{0}' and [riqi]>=convert(datetime,'{1} 00:00:00',120) and [riqi]<=convert(datetime,'{2} 23:59:59',120) and bs=0 and items.tizhong=1 order by jcxf.id", sdr["cardid"].ToString(), ktime, etime);
                    SqlCommand comm1 = new SqlCommand(sql1, conn1);
                    obj1 = comm1.ExecuteScalar();
                    try
                    {
                        if (obj1 != null)
                        {
                            maxcs = decimal.Parse(comm1.ExecuteScalar().ToString());
                        }
                        else
                        {
                            maxcs = decimal.Parse("0.00");
                        }
                    }
                    catch { maxcs = decimal.Parse("0.00"); }

                    //查询最小值并赋值
                    string sql2 = string.Format("SELECT  [bz] FROM [jcxf] join items on jcxf.xmid=items.iid where cardid='{0}' and [riqi]>=convert(datetime,'{1} 00:00:00',120) and [riqi]<=convert(datetime,'{2} 23:59:59',120) and bs=0 and items.tizhong=1 order by jcxf.id DESC", sdr["cardid"].ToString(), ktime, etime);
                    SqlCommand comm2 = new SqlCommand(sql2, conn2);
                    obj2 = comm2.ExecuteScalar();
                    try
                    {
                        if (obj2 != null)
                        {
                            mincs = decimal.Parse(comm2.ExecuteScalar().ToString());
                        }
                        else
                        {
                            mincs = decimal.Parse("0.00");
                        }
                    }
                    catch { mincs = decimal.Parse("0.00"); }

                    ce = maxcs - mincs;
                    dr["起始体重（公斤）"] = maxcs;
                    dr["当前体重（公斤）"] = mincs;
                    dr["差额（公斤）"] = ce;
                    dt.Rows.Add(dr);
                }



                dataGridView1.DataSource = dt;
                conn.Close();
            }
            else
            {
                string sqlc =string.Format("SELECT distinct mid, [mname] FROM [member] where mid='{0}'", textBox1.Text);
                SqlCommand comm = new SqlCommand(sqlc, conn);
                SqlDataReader sdr = comm.ExecuteReader();
                SqlConnection conn1 = new SqlConnection(constr);
                SqlConnection conn2 = new SqlConnection(constr);
                conn2.Open();
                decimal maxcs;
                decimal mincs;
                decimal ce;
                object obj1;
                object obj2;
                string ktime = dateTimePicker1.Text;
                string etime = dateTimePicker2.Text;
                conn1.Open();
                while (sdr.Read())
                {
                    DataRow dr = dt.NewRow();
                    if (textBox1.Text == string.Empty)
                    {
                        dr["卡号"] = sdr["cardid"].ToString();
                        dr["姓名"] = sdr["mname"].ToString();
                    }
                    else
                    {
                        dr["卡号"] = sdr["mid"].ToString();
                        dr["姓名"] = sdr["mname"].ToString();

                    }
                    //查询最大值与最小值并赋值
                    string sql1 = string.Format("SELECT  [bz] FROM [jcxf] join items on jcxf.xmid=items.iid where cardid='{0}' and [riqi]>=convert(datetime,'{1} 00:00:00',120) and [riqi]<=convert(datetime,'{2} 23:59:59',120) and bs=0 and items.tizhong=1 order by jcxf.id",textBox1.Text, ktime, etime);
                    SqlCommand comm1 = new SqlCommand(sql1, conn1);
                    obj1 = comm1.ExecuteScalar();
                    try
                    {
                        if (obj1 != null)
                        {
                            maxcs = decimal.Parse(comm1.ExecuteScalar().ToString());
                        }
                        else
                        {
                            maxcs = decimal.Parse("0.00");
                        }
                    }
                    catch { maxcs = decimal.Parse("0.00"); }

                    //查询最小值并赋值
                    string sql2 = string.Format("SELECT  [bz] FROM [jcxf] join items on jcxf.xmid=items.iid where cardid='{0}' and [riqi]>=convert(datetime,'{1} 00:00:00',120) and [riqi]<=convert(datetime,'{2} 23:59:59',120) and bs=0 and items.tizhong=1 order by jcxf.id DESC", textBox1.Text, ktime, etime);
                    SqlCommand comm2 = new SqlCommand(sql2, conn2);
                    obj2 = comm2.ExecuteScalar();
                    try
                    {
                        if (obj2 != null)
                        {
                            mincs = decimal.Parse(comm2.ExecuteScalar().ToString());
                        }
                        else
                        {
                            mincs = decimal.Parse("0.00");
                        }
                    }
                    catch { mincs = decimal.Parse("0.00"); }

                    ce = maxcs - mincs;
                    dr["起始体重（公斤）"] = maxcs;
                    dr["当前体重（公斤）"] = mincs;
                    dr["差额（公斤）"] = ce;
                    dt.Rows.Add(dr);
                }



                dataGridView1.DataSource = dt;
                conn.Close();


            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出Excel文件到";

            saveFileDialog.ShowDialog();

            // 这个一定要加上，要不然，点取消按钮就会提示“索引超出了数组界限”的错误。
            //用saveFileDialog.ShowDialog() == DialogResult.Cancle 不管用，会出现2次存储窗口。
            if (saveFileDialog.FileName == "")
            {

                return;
            }


            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string str = "";
            try
            {
                //写标题       
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += dataGridView1.Columns[i].HeaderText;
                }
                sw.WriteLine(str);
                //写内容    
                for (int j = 0; j < dataGridView1.Rows.Count; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < dataGridView1.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }
                        if (dataGridView1.Rows[j].Cells[k].Value != null)
                        {

                            tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
                        }
                        else
                        {
                            tempStr += "";
                        }
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
                MessageBox.Show("导出成功");
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
        e.RowBounds.Location.Y,
        dataGridView1.RowHeadersWidth - 4,
        e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
            dataGridView1.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void frmtizhongbianhua_Load(object sender, EventArgs e)
        {

        }

        private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (e.RowIndex < dataGridView1.Rows.Count - 1)
            {
                DataGridViewRow dgrSingle = dataGridView1.Rows[e.RowIndex];
                try
                {
                    if (decimal.Parse(dgrSingle.Cells[4].Value.ToString()) < 0)
                    {
                        dgrSingle.DefaultCellStyle.ForeColor = Color.Red;
                    }
                    else if (decimal.Parse(dgrSingle.Cells[4].Value.ToString()) > 0)
                    {
                        dgrSingle.DefaultCellStyle.ForeColor = Color.Blue;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
    }
}
